package com.qzyh.esb.egsa.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qzyh.esb.egsa.entity.MessageHeader;
import com.qzyh.esb.egsa.entity.MessageHeaderField;
import com.qzyh.esb.egsa.service.IMessageHeaderService;
import com.qzyh.esb.egsa.utils.FillUtil;
import com.qzyh.esb.egsa.utils.PageResultObject;
import com.qzyh.esb.egsa.utils.ResultObject;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

/**
 * <p>
 * 报文头信息表 前端控制器
 * </p>
 *
 * @author whq
 * @since 2023-11-02
 */
@RestController
@RequestMapping("/messageHeader")
public class MessageHeaderController {

    private static final Logger logger = LoggerFactory.getLogger(MessageHeaderController.class);

    @Autowired
    private IMessageHeaderService messageHeaderService;

    @GetMapping("/list")
    @ApiOperation(value = "查询报文头信息列表")
    public PageResultObject<MessageHeader> list(@ApiParam(value = "页码") @RequestParam("pageNum") Long pageNum,
                                                @ApiParam(value = "每页条数") @RequestParam("pageSize") Long pageSize,
                                                @ApiParam(value = "报文头名称") @RequestParam("name") String name) {
        IPage<MessageHeader> page = new Page<>(pageNum == null ? 0 : pageNum, pageSize == null ? 10 : pageSize);
        page = messageHeaderService.getList(page, name);
        PageResultObject<MessageHeader> pageResultObject = PageResultObject.success();
        pageResultObject.setPageNum(page.getCurrent());
        pageResultObject.setPageSize(page.getSize());
        pageResultObject.setTotal(page.getTotal());
        pageResultObject.setData(page.getRecords());
        return pageResultObject;
    }

    @PostMapping("/save")
    @ApiOperation(value = "保存报文头信息")
    public ResultObject save(@RequestBody MessageHeader messageHeader) {
        logger.info("请求参数：" + messageHeader.toString());
        messageHeader = (MessageHeader) FillUtil.fill(messageHeader);
        logger.info("填充后的信息：" + messageHeader.toString());
        boolean flag = messageHeaderService.saveOrUpdate(messageHeader);
        if (flag) return ResultObject.success("保存成功");
        else return ResultObject.fail("保存失败");
    }

    @GetMapping("/delete")
    @ApiOperation(value = "根据id删除报文头信息")
    public ResultObject deleteById(@ApiParam(value = "报文头id") @RequestParam("id") String id) {
        logger.info("删除报文头信息id：" + id);
        boolean flag = messageHeaderService.removeById(id);
        if (flag) return ResultObject.success("删除成功");
        else return ResultObject.fail("删除失败");
    }

    @GetMapping("/getMsgHeaderField")
    @ApiOperation(value = "根据报文头id获取报文头具体字段")
    public ResultObject<List<MessageHeaderField>> getMsgHeaderField(@ApiParam(value = "报文头id") @RequestParam("id") String id) {
        logger.info("报文头信息id：" + id);
        return messageHeaderService.getMsgHeaderFieldById(id);
    }

    @RequestMapping("/fileUpload")
    @ApiOperation(value = "报文头文件上传")
    public ResultObject fileUpload(@RequestParam("file") MultipartFile file, @RequestParam("id") String id) {
        if (file.isEmpty()) {
            logger.error("上传文件为空");
            return ResultObject.fail("文件上传失败");
        }
        String fileName = file.getOriginalFilename();
        String suffixName = fileName.substring(fileName.lastIndexOf(".") + 1);
        if (!"xlsx".equals(suffixName)) {
            logger.info("上传的文件【" + fileName + "】格式不符合");
            return ResultObject.fail("文件格式不是xlsx，文件上传失败。");
        }
        return messageHeaderService.parseFile(file, id);
    }

    @RequestMapping("/fileDownload")
    @ApiOperation(value = "报文头文件下载")
    public ResponseEntity<byte[]> fileDownload(@RequestParam("id") String id) {
        logger.info("报文头信息id：" + id);
        try {
            // 获取报文头名称，并将其设置为文件名
            String fileName = messageHeaderService.getFileNameById(id);
            // 生成Excel文件并输出
            XSSFWorkbook workbook = messageHeaderService.genExcel(id);
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            workbook.write(outputStream);
            workbook.close();
            // 设置响应头信息
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", URLEncoder.encode(fileName+".xlsx", "utf-8"));
            return new ResponseEntity<>(outputStream.toByteArray(), headers, HttpStatus.OK);
        } catch (IOException e) {
            logger.error("报文头文件下载失败，id：" + id);
            e.printStackTrace();
        }
        return null;
    }
}
